package com.shundr.shipper.common;

import java.text.Collator;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import android.app.Activity;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.ContactsContract;
import android.provider.ContactsContract.PhoneLookup;
import android.telephony.SmsManager;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.shundr.shipper.R;
import com.shundr.shipper.base.BaseActivity;
import com.shundr.shipper.common.adapter.ContactAdapter;
import com.shundr.shipper.common.adapter.ContactAdapter.OnInvitedListener;
import com.shundr.shipper.common.model.ContactInfo;
import com.shundr.shipper.common.model.InviteInfo;
import com.shundr.shipper.common.util.CommonConfig;
import com.shundr.shipper.common.util.JsonUtil;
import com.shundr.shipper.common.util.ProgressDialogHelper;
import com.shundr.shipper.common.util.ToastHelper;
import com.shundr.shipper.common.view.CListView;
import com.shundr.shipper.common.view.DialogInvitationFlag;
import com.shundr.shipper.common.view.DialogInvitationFlag.OnSendListener;
import com.shundr.shipper.frame.constant.LContext;
import com.shundr.shipper.frame.http.LHttpRequest;
import com.shundr.shipper.frame.util.StringUtil;
import com.shundr.shipper.user.http.UserRequest;

/**
 * 邀请用户 InvitationActivity
 * 
 * @author larry 2015-6-26 下午12:54:54
 * @version 1.0.0
 * 
 */
public class InvitationActivity extends BaseActivity implements OnClickListener {

	private static final int PAGE_SIZE = 1000;
	private int pageNo = 1;
	
	private EditText etPhone;
	private Button btnConfirm;
	private TextView tvFlag;
	private TextView tvNumber;
	private CListView mListView;
	private ContactAdapter mAdapter;
	
	private List<ContactInfo> mList;
	private List<ContactInfo> mChangeList = new ArrayList<ContactInfo>(); // 声明一个list，动态存储要显示的信息
	
	private List<String> mPhoneList = new ArrayList<String>(); // 声明一个list，动态存储要显示的信息
	
	private List<InviteInfo> mInvitedList = new ArrayList<InviteInfo>(); // 声明一个list，动态存储要显示的信息
	
	private Handler mHandler = new Handler(){

		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			switch (msg.what) {
			case UserRequest.GET_INVITE_SUCCESSED:
				List<InviteInfo> list = (List<InviteInfo>)msg.obj;
				mInvitedList.clear();
				mInvitedList.addAll(list);
				tvNumber.setText(list.size() + "");
				for(InviteInfo info : list){
					mPhoneList.add(info.getInvitePhone());
				}
				if(mList.size() > 0){
					for(ContactInfo contactInfo : mList){
						if(mPhoneList.contains(contactInfo.getPhone())){
							contactInfo.setInvitated(true);
						}
					}
					mAdapter.notifyDataSetChanged();
				}
				
				// 启动进程
				new GetContactTask().execute("");
				break;
			case 100:
				try {
					if (mList.size() == 0) {
						tvFlag.setVisibility(View.VISIBLE);
						mListView.setVisibility(View.GONE);
					} else {
						tvFlag.setVisibility(View.GONE);
						mListView.setVisibility(View.VISIBLE);
						// 按中文拼音顺序排序
						Comparator<ContactInfo> comp = new Mycomparator();
						Collections.sort(mList, comp);
						mAdapter = new ContactAdapter(mList, mContext);
						initAdatperListener(mList);
						mListView.setAdapter(mAdapter);
						mListView.setTextFilterEnabled(true);
					}
					ProgressDialogHelper.dismiss();
				} catch (Exception e) {
					e.printStackTrace();
				}
				break;
			case 101:
				mAdapter.notifyDataSetChanged();
				break;
			case LHttpRequest.REQUEST_FAILED:
				ProgressDialogHelper.dismiss();
				break;

			default:
				break;
			}
		}
		
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_invitation);
		initView();
		ProgressDialogHelper.show(mContext, "获取通讯录中,请稍候...");
		new UserRequest(mContext, mHandler).getInviteList(pageNo, PAGE_SIZE);
	}

	private void initView() {
		
		findViewById(R.id.layout_number).setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				if(mInvitedList.size() == 0)
					return;
				Intent intent = new Intent(mContext, InvitedActivity.class);
				intent.putExtra("json", JsonUtil.toJson(mInvitedList));
				startActivity(intent);
			}
		});
		
		etPhone = (EditText) findViewById(R.id.et_phone);
		etPhone.addTextChangedListener(new TextWatcher() {
			@Override
			public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
				mChangeList.clear();
				String phone = etPhone.getText().toString();
				if (!StringUtil.isNull(phone)) {
					for (ContactInfo info : mList) {
						if (info.getPhone().contains(phone)) {
							mChangeList.add(info);
						}
					}
					mAdapter.mList = mChangeList;
					initAdatperListener(mChangeList);
					mAdapter.notifyDataSetChanged();
				} else {
					mAdapter.mList = mList;
					initAdatperListener(mList);
					mAdapter.notifyDataSetChanged();
				}
			}
			@Override
			public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {}

			@Override
			public void afterTextChanged(Editable arg0) {}
		});
		btnConfirm = (Button) findViewById(R.id.btn_invitation);
		tvFlag = (TextView) findViewById(R.id.tv_flag);
		tvNumber = (TextView)findViewById(R.id.tv_number);

		btnConfirm.setOnClickListener(this);

		mListView = (CListView) findViewById(R.id.lv_list);
		mList = new ArrayList<ContactInfo>();
		mAdapter = new ContactAdapter(mList, mContext);
		initAdatperListener(mList);
	}
	
	private void initAdatperListener(final List<ContactInfo> list){
		mAdapter.setInvitedListener(new OnInvitedListener() {
			
			@Override
			public void OnInvited(final int position) {
				if(!LContext.isSimExist(mContext)){
					return;
				}
				DialogInvitationFlag flag = new DialogInvitationFlag(mContext);
				flag.setSendListener(new OnSendListener() {
					
					@Override
					public void onSend() {
						final ContactInfo info = list.get(position);
						new UserRequest(mContext, new Handler() {

							@Override
							public void handleMessage(Message msg) {
								super.handleMessage(msg);
								switch (msg.what) {
								case UserRequest.INVITE_REGISTER_SUCCESSED:
									sendSMS(info.getPhone(), CommonConfig.TEMPLATE_SEND_SMS);
									info.setInvitated(true);
//									mAdapter.notifyDataSetChanged();
									etPhone.setText("");
//									ToastHelper.toastLong(mContext,msg.obj.toString());
									new UserRequest(mContext, mHandler).getInviteList(pageNo, PAGE_SIZE);
									break;
								case LHttpRequest.REQUEST_FAILED:
									ToastHelper.toastLong(mContext,msg.obj.toString());
									break;

								default:
									break;
								}
							}

						}).inviteRegister(info.getName(), info.getPhone());
						
					}
				});
				flag.show(getSupportFragmentManager(), "");
			}
		});
	}

	// 获取通讯录进程
	private class GetContactTask extends AsyncTask<String, String, String> {
		public String doInBackground(String... params) {
			try {
				// 从本地手机中获取
				GetLocalContact();
				// 从SIM卡中获取
				GetSimContact("content://icc/adn");
				// 发现有得手机的SIM卡联系人在这个路径...所以都取了(每次验证是否已存在)
				GetSimContact("content://sim/adn");
			} catch (Exception e) {
				e.printStackTrace();
			}
			return "";
		}

		@Override
		protected void onPreExecute() {
		}

		@Override
		public void onPostExecute(String Re) {
			mHandler.sendEmptyMessage(100);
		}
	}

	// 从本机中取号
	private void GetLocalContact() {
		try {
			// 得到ContentResolver对象
			ContentResolver cr = getContentResolver();
			// 取得电话本中开始一项的光标
			Cursor cursor = cr.query(ContactsContract.Contacts.CONTENT_URI, null,null, null, null);
			while (cursor.moveToNext()) {
				ContactInfo cci = new ContactInfo();
				// 取得联系人名字
				int nameFieldColumnIndex = cursor.getColumnIndex(PhoneLookup.DISPLAY_NAME);
				cci.setName(cursor.getString(nameFieldColumnIndex));

				// 取得联系人ID
				int id = cursor.getInt(cursor
						.getColumnIndex(ContactsContract.Contacts._ID));
				Cursor phone = cr.query(
						ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
						ContactsContract.CommonDataKinds.Phone.CONTACT_ID + "=?",
						new String[] { Integer.toString(id) }, null);// 再类ContactsContract.CommonDataKinds.Phone中根据查询相应id联系人的所有电话；

				// 取得电话号码(可能存在多个号码)
				while (phone.moveToNext()) {
					String strPhoneNumber = phone
							.getString(phone
									.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
					cci.setPhone(GetNumber(strPhoneNumber));
					if(mPhoneList.contains(cci.getPhone())){
						cci.setInvitated(true);
					}else{
						cci.setInvitated(false);
					}
					if(IsUserNumber(cci.getPhone()) && !IsContain(mList, cci.getPhone())){
						mList.add(cci);
					}
				}
				phone.close();
			}
			cursor.close();
		} catch (Exception e) {
			e.printStackTrace();
			tvFlag.setVisibility(View.VISIBLE);
			mListView.setVisibility(View.GONE);
			ProgressDialogHelper.dismiss();
		}
	}

	// 从SIM卡中取号
	private void GetSimContact(String add) {
		// 读取SIM卡手机号,有两种可能:content://icc/adn与content://sim/adn
		try {
			Intent intent = new Intent();
			intent.setData(Uri.parse(add));
			Uri uri = intent.getData();
			Cursor mCursor = getContentResolver().query(uri, null, null, null,
					null);
			if (mCursor != null) {
				while (mCursor.moveToNext()) {
					ContactInfo sci = new ContactInfo();
					// 取得联系人名字
					int nameFieldColumnIndex = mCursor.getColumnIndex("name");
					sci.setName(mCursor.getString(nameFieldColumnIndex));
					// 取得电话号码
					int numberFieldColumnIndex = mCursor.getColumnIndex("number");
					sci.setPhone(mCursor.getString(numberFieldColumnIndex));
					sci.setPhone(GetNumber(sci.getPhone()));
					if(mPhoneList.contains(sci.getPhone())){
						sci.setInvitated(true);
					}else{
						sci.setInvitated(false);
					}
					if(IsUserNumber(sci.getPhone()) && !IsContain(mList, sci.getPhone())){
						mList.add(sci);
					}
				}
				mCursor.close();
			}
		} catch (Exception e) {
			e.printStackTrace();
			tvFlag.setVisibility(View.VISIBLE);
			mListView.setVisibility(View.GONE);
			ProgressDialogHelper.dismiss();
		}
	}

	// 通讯录按中文拼音排序
	private class Mycomparator implements Comparator<ContactInfo> {
		public int compare(ContactInfo o1, ContactInfo o2) {
			Comparator<Object> cmp = Collator.getInstance(java.util.Locale.CHINA);
			return cmp.compare(o1.getName(), o2.getName());
		}

	}
	
	// 是否在LIST有值
	private boolean IsContain(List<ContactInfo> list, String un) {
		for (int i = 0; i < list.size(); i++) {
			if (un.equals(list.get(i).getPhone())) {
				return true;
			}
		}
		return false;
	}

	// 还原11位手机号 包括去除“-”
	private static String GetNumber(String num2) {
		String num;
		if (num2 != null) {
			num = num2.replaceAll("-", "");
			if (num.startsWith("+86")) {
				num = num.substring(3);
			} else if (num.startsWith("86")) {
				num = num.substring(2);
			} else if (num.startsWith("86")) {
				num = num.substring(2);
			}
		} else {
			num = "";
		}
		return num.replace(" ", "");
	}
	
	// 是否为手机号码 有的通讯录格式为135-1568-1234
	private static boolean IsUserNumber(String num) {
		boolean re = false;
		if (num.length() >= 11) {
			if (num.startsWith("1")) {
				re = true;
			}

		}
		return re;
	}
	
	/**
	 * 发送成功
	 * sendSMS(这里用一句话描述这个方法的作用)
	 * (这里描述这个方法适用条件 – 可选)
	 * @param phoneNum
	 * @param message
	 * void
	 * @exception
	 * @since  1.0.0
	 */
	private void sendSMS(String phoneNum, String message) {
		// 初始化发短信SmsManager类
		SmsManager smsManager = SmsManager.getDefault();
		
		/* 建立自定义Action常数的Intent(给PendingIntent参数之用) */  
        Intent itSend = new Intent(SMS_SEND_ACTIOIN);  
        /* sentIntent参数为传送后接受的广播信息PendingIntent */  
        PendingIntent mSendPI = PendingIntent.getBroadcast(getApplicationContext(), 0, itSend, 0);  
        /* 发送SMS短信，注意倒数的两个PendingIntent参数 */  
		if (message.length() > 70) {
			ArrayList<String> msgs = smsManager.divideMessage(message);
			for (String msg : msgs) {
				smsManager.sendTextMessage(phoneNum, null, msg, mSendPI, null); 
			}
		} else {
			smsManager.sendTextMessage(phoneNum, null, message, mSendPI, null); 
		}
	}
	
	/* 建立两个mServiceReceiver对象，作为类成员变量 */
	private mServiceReceiver mReceiver01;
	/* 自定义ACTION常数，作为广播的Intent Filter识别常数 */
	private static String SMS_SEND_ACTIOIN = "SMS_SEND_ACTIOIN";
	// 这是重载Activity中的函数
	@Override
	protected void onResume() {
		/* 自定义IntentFilter为SENT_SMS_ACTIOIN Receiver */
		IntentFilter mFilter01;
		mFilter01 = new IntentFilter(SMS_SEND_ACTIOIN);
		mReceiver01 = new mServiceReceiver();
		registerReceiver(mReceiver01, mFilter01);
		super.onResume();
	}

	@Override
	protected void onPause() {
		/* 取消注册自定义Receiver */
		unregisterReceiver(mReceiver01);
		super.onPause();
	}
	
	/* 自定义mServiceReceiver重写BroadcastReceiver监听短信状态信息 */
	public class mServiceReceiver extends BroadcastReceiver {
		@Override
		public void onReceive(Context context, Intent intent) {
			if (intent.getAction().equals(SMS_SEND_ACTIOIN)) {
				try {
					switch (getResultCode()) {
					case Activity.RESULT_OK:
						/* 发送短信成功 */
						ToastHelper.toastShort(mContext, "邀请成功");
						break;
					case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
						/* 发送短信失败 */
						ToastHelper.toastShort(mContext, "发送短信失败");
						break;
					case SmsManager.RESULT_ERROR_RADIO_OFF:
						break;
					case SmsManager.RESULT_ERROR_NULL_PDU:
						break;
					}
				} catch (Exception e) {
					e.getStackTrace();
				}
			}
		}
	}

	@Override
	protected void onDestroy() {
		try {
			mList.clear();
			mList = null;
		} catch (Exception e) {
			e.printStackTrace();
		}
		super.onDestroy();
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btn_invitation:
			final String phone = etPhone.getText().toString();
			if(!StringUtil.isNull(phone)){
				if(!StringUtil.isMobileNO(phone)){
					ToastHelper.toastLong(mContext, "请输入正确手机号");
				}else{
					if(!LContext.isSimExist(mContext)){
						return;
					}
					DialogInvitationFlag flag = new DialogInvitationFlag(mContext);
					flag.setSendListener(new OnSendListener() {
						
						@Override
						public void onSend() {
							new UserRequest(mContext, new Handler() {

								@Override
								public void handleMessage(Message msg) {
									super.handleMessage(msg);
									switch (msg.what) {
									case UserRequest.INVITE_REGISTER_SUCCESSED:
										ToastHelper.toastLong(mContext,msg.obj.toString());
										new UserRequest(mContext, mHandler).getInviteList(pageNo, PAGE_SIZE);
										sendSMS(phone, CommonConfig.TEMPLATE_SEND_SMS);//邀请
										break;
									case LHttpRequest.REQUEST_FAILED:
										ToastHelper.toastLong(mContext,msg.obj.toString());
										break;

									default:
										break;
									}
								}

							}).inviteRegister("", phone);
						}
					});
					flag.show(getSupportFragmentManager(), "");
				}
			}else{
				ToastHelper.toastLong(mContext, "请输入手机号");
			}
			break;

		default:
			break;
		}
	}

}
